package com.zzj.ecology.framework.configs.security.listener;

import com.zzj.ecology.common.constant.LogConstants;
import com.zzj.ecology.framework.manager.AsyncManager;
import com.zzj.ecology.framework.manager.async.AsyncTaskFactory;
import com.zzj.ecology.system.bean.minitor.SysUserOnline;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.web.session.HttpSessionEventPublisher;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import java.util.Date;

/**
 * 监听 HttpSession 创建与销毁
 */
@Component
public class CustomizeHttpSessionListener extends HttpSessionEventPublisher {

    private static final Logger logger = LoggerFactory.getLogger(CustomizeHttpSessionListener.class);

    @Autowired
    private AsyncManager asyncManager;
    @Autowired
    private AsyncTaskFactory asyncTaskFactory;

    @Autowired
    private SessionRegistry sessionRegistry;

    @Override
    public void sessionCreated(HttpSessionEvent event) {
        super.sessionCreated(event);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        HttpSession session = event.getSession();
        logger.info("{}.sessionDestroyed() --> 销毁Session: {}, {}",this.getClass().getName(), session.getId(), sessionRegistry.getAllPrincipals().size());

        // 把当前的sessionid 状态设置成 off_line
        SysUserOnline sysUserOnline = new SysUserOnline(LogConstants.OnlineLog.STATUS_OFFLINE, session.getId());
        sysUserOnline.setLastAccessTime(new Date());
        asyncManager.execute(asyncTaskFactory.updateOnlineInfo(sysUserOnline));

        super.sessionDestroyed(event);
    }
}
